import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/home/home_background.dart';
import 'package:material_collection_app/widget/home/home_data_card.dart';
import 'package:material_collection_app/widget/home/home_grid_card.dart';
import 'package:material_collection_app/widget/home/home_notice.dart';
import 'package:material_collection_app/widget/home/home_user_info.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<HomePage> {
  Map userInfo = {
    'name': '',
    'avatar': ''
  };
  bool loadSuccess = false;
  DateTime lastPopTime;
  List noticeList;
  bool noticeLoadSuccess = false;
  Map showData = {
    'enter': 0,
    'out': 0,
    'all': 0
  };

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    _getNotice();
    _getDataShow();
  }

  // 获取用户信息
  _getUserInfo() {
    Utils.getUserId().then((userId) =>  {
      DioUtils.request("common/getDetails",
        context: context,
        method: "POST",
        params: {
          'id': userId
        },
        onSuccess: (res) {
          if(res['code'] == 1) {
            // UserModel userModel = UserModel.fromJson(res['data']);
            setState(() {
              loadSuccess = true;
              userInfo = res['data'];
            });
          }else {
            Utils.showText(text: res['msg']);
          }
        },
        onError: (error) {
          // Toast.show(error);
        }
      )
    });
  }

  // 获取数据展示
  _getDataShow() {
    DioUtils.request("Common/getDataShow",
      context: context,
      method: "GET",
      onSuccess: (res) {
        if(res['code'] == 1) {
          setState(() {
            showData = res['data'];
          });
        }else {
          Utils.showText(text: res['msg']);
        }
      },
      onError: (error) {
        // Toast.show(error);
      }
    );
  }

  // 获取通知
  _getNotice({bool loadMore = false, bool screen}) async {
    loadSuccess = false;

    DioUtils.request("common/getMyMsgList",
      context: context,
      method: "GET",
      onSuccess: (res) {
        if(res['code'] == 1) {
          if(mounted) {
            print(res["data"]["data"]);
            setState(() {
              noticeList = res["data"]["data"];
              noticeLoadSuccess = true;
            });
          }
        }else {
          Utils.showText(text: res['msg']);
        }
      },
      onError: (error) {}
    );
  }

  // 点击两次返回才退出APP
  Future<bool> _onWillPop() async{
    if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: 2)){
      lastPopTime = DateTime.now();
      Utils.showText(text: ' 再次点击退出 ', radius: 40, align: Alignment(0, 0.6));
      return false;
    }else{
      lastPopTime = DateTime.now();
      // 退出app
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      return true;
    }
  }

  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        body: Container(
          height: double.infinity,
          color: Utils.hexToColor('#F5F6FA'),
          child: SingleChildScrollView(
            child: Stack(
              children: <Widget>[
                HomeBackground(),
                HomeUserInfo(userInfo: userInfo, loadSuccess: loadSuccess),
                HomeNotice(list: noticeList, loadSuccess: noticeLoadSuccess),
                HomeDataCard(showData: showData),
                HomeGridCard()
              ]
            )
          )
        )
      ),
      onWillPop: _onWillPop
    );
  }
}